<template>
  <!-- 校园看点轮播图部分 -->
  <div class="bg-gray-50 py-16">
    <!-- 标题部分使用常规宽度 -->
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 mb-10">
      <div class="flex items-center justify-between mb-10">
        <div class="flex items-center">
          <div class="w-1 h-12 bg-[#F05454] mr-4"></div>
          <div>
            <h2 class="text-3xl font-bold text-[#333333] leading-tight">校园看点</h2>
            <p class="text-gray-500 mt-1">分享校园精彩瞬间，记录美好校园生活</p>
          </div>
        </div>
        <div class="flex items-center space-x-3">
          <button type="button" @click.stop="prevCampusSlide" class="w-10 h-10 rounded-full flex items-center justify-center bg-white shadow-md hover:bg-[#F05454] hover:text-white text-[#333333] transition-all transform hover:-translate-y-1 cursor-pointer z-20">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
            </svg>
          </button>
          <button type="button" @click.stop="nextCampusSlide" class="w-10 h-10 rounded-full flex items-center justify-center bg-white shadow-md hover:bg-[#F05454] hover:text-white text-[#333333] transition-all transform hover:-translate-y-1 cursor-pointer z-20">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
            </svg>
          </button>
        </div>
      </div>
    </div>

    <!-- 轮播图部分使用全宽布局 -->
    <div class="relative overflow-hidden">
      <div class="flex transition-transform duration-500 ease-in-out" :style="{ transform: `translateX(-${campusActiveSlide * 100}%)` }">
        <div v-for="(item, index) in campusNews" :key="item.id || index"
             :class="`flex-shrink-0 ${campusVisibleSlides === 1 ? 'w-full' : campusVisibleSlides === 2 ? 'w-1/2' : campusVisibleSlides === 3 ? 'w-1/3' : campusVisibleSlides === 4 ? 'w-1/4' : 'w-1/5'}`">
          <div
            class="mx-2 bg-white rounded-md overflow-hidden shadow-md hover:shadow-lg group h-full cursor-pointer transform hover:-translate-y-1 article-card"
            @click="handleArticleClick(item, $event)"
            :title="`点击查看文章：${item.title}`"
          >
            <div class="relative overflow-hidden aspect-square">
              <img
                :src="item.image"
                :alt="item.title"
                class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110"
                @error="handleImageError"
                loading="lazy"
              >
              <div class="absolute inset-0 bg-gradient-to-t from-black/60 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>
              <!-- 添加点击提示图标 -->
              <div class="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity duration-300">
                <div class="bg-white/90 rounded-full p-1.5 shadow-md">
                  <svg class="w-4 h-4 text-[#F05454]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"></path>
                  </svg>
                </div>
              </div>
            </div>
            <div class="p-4">
              <h3 class="text-base font-medium text-[#333333] group-hover:text-[#F05454] transition-colors line-clamp-2">{{ item.title }}</h3>
              <div class="flex items-center mt-2 text-xs text-gray-500">
                <span>{{ item.date }}</span>
                <span class="mx-2">|</span>
                <span>{{ item.category }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 指示器 -->
    <div class="flex justify-center mt-10 space-x-3 mb-4">
      <button
          v-for="(_, index) in totalPages"
          :key="index"
          @click="campusActiveSlide = index"
          :class="`h-3 rounded-full transition-all duration-300 ${campusActiveSlide === index ? 'bg-[#F05454] w-8' : 'bg-gray-300 w-3 hover:bg-gray-400'}`"
      ></button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, onUnmounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { homeApi, articleApi, API_BASE_URL } from '@/utils/api';

// Vue Router实例
const router = useRouter();

// 定义emit
const emit = defineEmits(['api-error']);

// 校园看点轮播图相关数据和方法
const campusActiveSlide = ref(0);
const campusVisibleSlides = ref(5); // 同时显示的卡片数量
const campusNews = ref([]);
const error = ref(null);

// 计算总页数
const totalPages = computed(() => {
  if (campusNews.value.length === 0) return 0;
  return Math.ceil(campusNews.value.length / campusVisibleSlides.value);
});

// 从HTML内容中提取第一张图片URL的函数
const extractFirstImageFromHtml = (htmlContent) => {
  if (!htmlContent) return null;

  try {
    // 创建一个临时的DOM元素来解析HTML
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = htmlContent;

    // 查找所有img标签
    const images = tempDiv.querySelectorAll('img');

    // 遍历图片，找到第一个有效的图片URL
    for (let i = 0; i < images.length; i++) {
      const img = images[i];
      let src = img.getAttribute('src') || img.getAttribute('data-src');

      if (src && src.trim() !== '') {
        src = src.trim();

        // 跳过base64图片和占位符图片
        if (src.startsWith('data:') ||
            src.includes('placeholder') ||
            src.includes('loading') ||
            src.includes('blank.gif') ||
            src.includes('spacer.gif')) {
          continue;
        }

        // 处理不同类型的URL
        if (src.startsWith('http://') || src.startsWith('https://')) {
          // 绝对URL，直接返回
          return src;
        } else if (src.startsWith('//')) {
          // 协议相对URL，添加http协议
          return `http:${src}`;
        } else if (src.startsWith('/')) {
          // 根相对路径，添加基础URL
          return `${API_BASE_URL}${src}`;
        } else {
          // 相对路径，添加基础URL和斜杠
          return `${API_BASE_URL}/${src}`;
        }
      }
    }

    // 如果没有找到img标签，尝试使用正则表达式匹配
    const imgRegex = /<img[^>]+src\s*=\s*["']([^"']+)["'][^>]*>/gi;
    let match;
    while ((match = imgRegex.exec(htmlContent)) !== null) {
      let src = match[1];
      if (src && src.trim() !== '') {
        src = src.trim();

        // 跳过base64图片和占位符图片
        if (src.startsWith('data:') ||
            src.includes('placeholder') ||
            src.includes('loading') ||
            src.includes('blank.gif') ||
            src.includes('spacer.gif')) {
          continue;
        }

        // 处理URL
        if (src.startsWith('http://') || src.startsWith('https://')) {
          return src;
        } else if (src.startsWith('//')) {
          return `http:${src}`;
        } else if (src.startsWith('/')) {
          return `${API_BASE_URL}${src}`;
        } else {
          return `${API_BASE_URL}/${src}`;
        }
      }
    }

  } catch (e) {
    console.warn('解析HTML内容时出错:', e);
  }

  return null; // 没有找到有效图片
};

// 格式化日期的函数
const formatDate = (dateString) => {
  if (!dateString) return '';

  try {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    });
  } catch (e) {
    return dateString;
  }
};

// 图片加载错误处理函数
const handleImageError = (event) => {
  console.warn('图片加载失败:', event.target.src);
  // 设置默认图片
  event.target.src = '';
  event.target.alt = '图片加载失败';
};

// 文章卡片点击跳转函数
const handleArticleClick = (article, event) => {
  try {
    // 验证文章ID是否有效
    if (!article.id) {
      console.error('文章ID无效:', article);
      return;
    }

    // 构建跳转URL
    const targetUrl = `/news/${article.id}`;

    // 检查是否按住Ctrl/Cmd键，如果是则在新标签页打开，否则在当前标签页打开
    const openInNewTab = event?.ctrlKey || event?.metaKey || true; // 默认在新标签页打开

    if (openInNewTab) {
      // 在新标签页打开
      try {
        const routeData = router.resolve({ path: targetUrl });
        window.open(routeData.href, '_blank');
      } catch (routerError) {
        console.warn('Vue Router解析失败，使用Hash模式URL:', routerError);
        const baseUrl = window.location.origin;
        const fullUrl = `${baseUrl}/#${targetUrl}`;
        window.open(fullUrl, '_blank');
      }
    } else {
      // 在当前标签页打开
      router.push(targetUrl);
    }

  } catch (error) {
    console.error('跳转文章详情页失败:', error);
    const baseUrl = window.location.origin;
    const fallbackUrl = `${baseUrl}/#/news/${article.id}`;
    window.open(fallbackUrl, '_blank');
  }
};

// 获取校园看点数据（从文章API获取）
const fetchCampusHighlights = async () => {
  error.value = null;
  try {
    // 使用配置好的API方法获取最新文章
    const response = await articleApi.getArticleList({
      limit: 30, // 获取30篇文章，然后过滤出有图片的
      page: 1
    });

    let articlesWithImages = [];

    // 处理返回的数据
    let articles = [];
    
    if (response) {
      // 尝试多种可能的响应结构
      if (Array.isArray(response.list)) {
        articles = response.list;
      } else if (Array.isArray(response.data?.list)) {
        articles = response.data.list;
      } else if (Array.isArray(response)) {
        articles = response;
      } else if (Array.isArray(response.data)) {
        articles = response.data;
      } else if (response.data && Array.isArray(response.data)) {
        articles = response.data;
      } else {
        console.warn('无法识别的API响应结构:', response);
      }
      
      if (articles.length === 0) {
        console.warn('API返回空文章列表:', response);
      }
    } else {
      console.warn('API响应无效:', response);
      return;
    }
    
    // 确保articles是数组
    if (!Array.isArray(articles)) {
      console.warn('最终articles不是数组:', articles);
      articles = [];
    }

    // 批量获取文章详情，限制并发数量以避免服务器压力
    const maxConcurrent = 5; // 最多同时请求5篇文章的详情
    const targetCount = 15; // 目标获取15篇有图片的文章

    for (let i = 0; i < articles.length && articlesWithImages.length < targetCount; i += maxConcurrent) {
      // 创建当前批次的请求
      const batch = articles.slice(i, i + maxConcurrent);
      const promises = batch.map(async (article) => {
        try {
          // 使用配置好的API方法获取文章详情
          const articleDetail = await articleApi.getArticleDetail(article.newsId);
          
          // 尝试多种可能的HTML内容字段
          const htmlContent = articleDetail.data?.content || 
                             articleDetail.data?.content_html || 
                             articleDetail.content || 
                             articleDetail.content_html || 
                             '';
          
          // 从HTML内容中提取第一张图片
          const imageUrl = extractFirstImageFromHtml(htmlContent);
          
          // 如果从HTML中没提取到图片，尝试使用文章封面图
          if (!imageUrl && articleDetail.data?.coverImage) {
            return {
              id: article.newsId,
              title: article.title,
              image: articleDetail.data.coverImage,
              date: formatDate(article.pubTime),
              category: article.category || article.section || '校园动态',
              link: `/news/${article.newsId}`
            };
          }

          if (imageUrl) {
            return {
              id: article.newsId,
              title: article.title,
              image: imageUrl,
              date: formatDate(article.pubTime),
              category: article.category || article.section || '校园动态',
              link: `/news/${article.newsId}`
            };
          }
          return null;
        } catch (detailErr) {
          if (!detailErr.message.includes('timeout')) {
            console.warn(`获取文章详情失败:`, detailErr);
          }
          return null;
        }
      });

      // 等待当前批次完成
      const results = await Promise.all(promises);

      // 添加有效结果
      for (const result of results) {
        if (result && articlesWithImages.length < targetCount) {
          articlesWithImages.push(result);
        }
      }
    }

    campusNews.value = articlesWithImages;

    // 如果没有找到有图片的文章，显示错误信息
    if (campusNews.value.length === 0) {
      error.value = '暂无包含图片的校园看点数据';
    }

  } catch (err) {
    console.error('获取校园看点数据失败:', err);
    // 触发API错误事件，让父组件处理
    emit('api-error', err);
  }
};

// 切换到上一页幻灯片
const prevCampusSlide = () => {
  if (campusActiveSlide.value > 0) {
    // 向前移动一页
    campusActiveSlide.value--;
  } else {
    // 如果已经在第一页，则跳到最后一页
    campusActiveSlide.value = totalPages.value - 1;
  }
};

// 切换到下一页幻灯片
const nextCampusSlide = () => {
  if (campusActiveSlide.value < totalPages.value - 1) {
    // 向后移动一页
    campusActiveSlide.value++;
  } else {
    // 如果已经是最后一页，则返回第一页
    campusActiveSlide.value = 0;
  }
}
</script>
